package com.hqyj.finance.server.invest.financeinvest.service.impl;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hqyj.finance.server.invest.financeinvest.entity.UserStock;
import com.hqyj.finance.server.invest.financeinvest.mapper.UserStockMapper;
import com.hqyj.finance.server.invest.financeinvest.service.UserStockService;
import com.hqyj.finance.server.invest.financeinvest.views.UserStockKLineGraphicView;
import com.hqyj.finance.server.invest.financeinvest.views.UserStockView;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.management.Query;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

@Service
public class UserStockServiceImpl extends ServiceImpl<UserStockMapper, UserStock> implements UserStockService {

    @Value("${myproject.ig507-licence}")
    private String licence;

    @Resource
    private UserStockMapper userStockMapper;

    @Override
    public boolean saveUserStock(UserStock userStock) throws Exception {
        return super.save(userStock);
    }

    @Override
    public List<UserStock> queryUserStockListByUid(Integer uid) throws Exception {
        QueryWrapper<UserStock> userStockQueryWrapper = new QueryWrapper<UserStock>();
        userStockQueryWrapper.eq("stockUserId", uid);
        return super.list(userStockQueryWrapper);
    }

    @Override
    public String queryUserStockRealInfoByStockCode(String code) throws Exception {
        return HttpUtil.get("https://ig507.com/data/time/real/" + code + "?licence=" + this.licence);
    }

    @Override
    public List<UserStockView> queryUserStockViewByUid(Integer uid) throws Exception {
        List<UserStockView> userStockViewList = new ArrayList<UserStockView>();
        List<UserStock> userStocks = queryUserStockListByUid(uid);

        for (UserStock userStock : userStocks) {
            String result = queryUserStockRealInfoByStockCode(userStock.getStockCode());
            System.out.println("股票代码为：" + userStock.getStockCode());
            System.out.println("----------实时股票数据---------");
            System.out.println(result);
            JSONObject jsonResult = JSONUtil.parseObj(result);
            System.out.println("最新价格是：" + jsonResult.get("p"));
            UserStockView userStockView = new UserStockView();
            userStockView.setId(userStock.getStockId());
            userStockView.setStockUser(userStock.getStockUser());
            userStockView.setStockUserId(userStock.getStockUserId());
            userStockView.setStockCode(userStock.getStockCode());
            userStockView.setStockName(userStock.getStockName());
            userStockView.setStockPrice(userStock.getStockPrice());
            userStockView.setStockNum(userStock.getStockNum());
            userStockView.setStockTime(userStock.getStockTime());
            userStockView.setStockType(userStock.getStockType());
            Double tempStockMarketValue = Double.parseDouble(userStockView.getStockPrice()) * Double.parseDouble(userStockView.getStockNum()) * 100;
            //取小数点后的两位。
            DecimalFormat df = new DecimalFormat("#.00");
            String tempResult = df.format(tempStockMarketValue);
            userStockView.setStockMarketValue(tempResult);

            userStockView.setCurrentStockPrice(jsonResult.get("p").toString());
            tempStockMarketValue = Double.parseDouble(userStockView.getCurrentStockPrice()) * Double.parseDouble(userStockView.getStockNum()) * 100;
            //df = new DecimalFormat("#.00");
            tempResult = df.format(tempStockMarketValue);
            userStockView.setCurrentMarketValue(tempResult);
            Double tempProfitLoss = Double.parseDouble(userStockView.getCurrentMarketValue()) - Double.parseDouble(userStockView.getStockMarketValue());
            tempResult = df.format(tempProfitLoss);
            userStockView.setProfileLoss(tempResult);

            userStockViewList.add(userStockView);

        }
        return userStockViewList;
    }

    @Override
    public UserStockKLineGraphicView queryUserStockLineGraphicViewByCode(String code, String type) throws Exception {
        String stockDetailsInfoApi = "https://ig507.com/data/time/f10/info/" + code + "?licence=" + this.licence;

        String dayLineCallApi = "https://ig507.com/data/time/history/trade/" + code + "/Day_qfq?licence=" + this.licence; //日线级别的api接口
        String weekLineCallApi = "https://ig507.com/data/time/history/trade/" + code + "/Week_qfq?licence=" + this.licence;
        String monthLineCallApi = "https://ig507.com/data/time/history/trade/" + code + "/Month_qfq?licence=" + this.licence;
        String yearLineCallApi = "https://ig507.com/data/time/history/trade/" + code + "/Year_qfq?licence=" + this.licence;

        UserStockKLineGraphicView userStockKLineGraphicView = new UserStockKLineGraphicView();

        //1.根据股票代码查询这个股票的详细信息
        String stockDetailsResult = HttpUtil.get(stockDetailsInfoApi, CharsetUtil.CHARSET_UTF_8); //添加字符集参数，避免出现中文乱码;
        JSONObject stockDetailsJsonObj = JSONUtil.parseObj(stockDetailsResult);
        userStockKLineGraphicView.setStockCode(code);
        userStockKLineGraphicView.setStockName(stockDetailsJsonObj.get("name").toString());
        userStockKLineGraphicView.setMarket(stockDetailsJsonObj.get("market").toString());
        userStockKLineGraphicView.setRealgu(stockDetailsJsonObj.get("realgu").toString());

        //2.获取对应的k线图的数据集合
        String kLineDataResult = "";
        switch (type) {
            case "day":
                kLineDataResult = HttpUtil.get(dayLineCallApi, CharsetUtil.CHARSET_UTF_8);
                break;
            case "week":
                kLineDataResult = HttpUtil.get(weekLineCallApi, CharsetUtil.CHARSET_UTF_8);
                break;
            case "month":
                kLineDataResult = HttpUtil.get(monthLineCallApi, CharsetUtil.CHARSET_UTF_8);
                break;
            case "year":
                kLineDataResult = HttpUtil.get(yearLineCallApi, CharsetUtil.CHARSET_UTF_8);
                break;
        }
        System.out.println("--------------K线数据------------");
        System.out.println(kLineDataResult);
        JSONArray jsonArray = JSONUtil.parseArray(kLineDataResult);


        int len = jsonArray.size();
        int targetLength = -1;
        if ("day".equals(type) || "week".equals(type)) {
            if (len > 90) {
                //只取出90天的数据；
                targetLength = 90;
            } else {
                targetLength = len;
            }
        } else if ("month".equals(type)) {
            if (len > 60) {
                targetLength = 60;
            } else {
                targetLength = len;
            }
        } else if ("year".equals(type)) {
            if (len > 10) {
                targetLength = 10;
            } else {
                targetLength = len;
            }
        }

        for (int i = len-1; i > len-targetLength; i--) {
            Object tempObj = jsonArray.get(i);
            JSONObject tempJsonObj = JSONUtil.parseObj(tempObj);

            List<Object> tempList = new ArrayList<Object>();
            tempList.add(tempJsonObj.get("d").toString());
            tempList.add(Double.parseDouble(tempJsonObj.get("o").toString()));
            tempList.add(Double.parseDouble(tempJsonObj.get("c").toString()));
            tempList.add(Double.parseDouble(tempJsonObj.get("l").toString()));
            tempList.add(Double.parseDouble(tempJsonObj.get("h").toString()));
            userStockKLineGraphicView.getData().add(tempList);
        }
        Collections.reverse(userStockKLineGraphicView.getData());
        return userStockKLineGraphicView;
    }
}
